﻿using System;
using System.ComponentModel.Composition.Hosting;
using System.Diagnostics.CodeAnalysis;
using System.Reflection;
using System.Security;

namespace Songhay.Composition
{
    /// <summary>
    /// Static members for MEF Composition.
    /// </summary>
    public static partial class CompositionUtility
    {
        /// <summary>
        /// Gets the MEF assembly catalog of exports
        /// from the specified <see cref="System.Reflection.Assembly"/>.
        /// </summary>
        /// <param name="dll">The DLL.</param>
        /// <returns>Returns <see cref="System.ComponentModel.Composition.Hosting.AssemblyCatalog"/>.</returns>
        public static AssemblyCatalog GetAssemblyCatalog(Assembly dll)
        {
            return new AssemblyCatalog(dll);
        }

        /// <summary>
        /// Gets the MEF assembly catalog of exports.
        /// </summary>
        /// <param name="pathToAssembly">The path to assembly.</param>
        [SecurityCritical]
        [SuppressMessage("Microsoft.Reliability", "CA2000:DisposeObjectsBeforeLosingScope",
            Justification = "Reliable disposal depends on callers.")]
        public static AssemblyCatalog GetAssemblyCatalog(string pathToAssembly)
        {

#if SILVERLIGHT
            var dll = Assembly.Load(pathToAssembly);
#endif

#if !SILVERLIGHT
            var dll = Assembly.LoadFile(pathToAssembly);
#endif

            var assemblyCatalog = new AssemblyCatalog(dll);
            return assemblyCatalog;
        }

        /// <summary>
        /// Gets the MEF assembly catalog of exports
        /// from the specified <see cref="System.Type"/>.
        /// </summary>
        /// <param name="type">The type.</param>
        /// <returns>
        /// Returns <see cref="System.ComponentModel.Composition.Hosting.AssemblyCatalog"/>.
        /// </returns>
        public static AssemblyCatalog GetAssemblyCatalog(Type type)
        {
            if(type == null) return null;
            return new AssemblyCatalog(type.Assembly);
        }
    }
}
